package pl.th.permission.plugin

import com.android.build.api.transform.QualifiedContent
import com.android.build.api.transform.Transform
import com.android.build.api.transform.TransformException
import com.android.build.api.transform.TransformInvocation
import com.android.build.gradle.AppExtension
import com.android.build.gradle.internal.pipeline.TransformManager
import org.gradle.api.Plugin
import org.gradle.api.Project
import pl.th.permission.plugin.transform.Transformer

public class PermissionCompatPlugin extends Transform implements Plugin<Project> {

    private static final String PLUGIN_TASK_NAME = "injectPermissionTask"

    private PermissionExtension permissionExt

    @Override
    void apply(Project project) {
        project.extensions.add("permission", PermissionExtension)
        permissionExt = project.getExtensions().getByType(PermissionExtension)
        def appExtension = project.extensions.getByType(AppExtension)
        appExtension.registerTransform(this)
    }

    @Override
    String getName() {
        return PLUGIN_TASK_NAME
    }

    @Override
    Set<QualifiedContent.ContentType> getInputTypes() {
        return TransformManager.CONTENT_CLASS
    }

    @Override
    Set<? super QualifiedContent.Scope> getScopes() {
        return TransformManager.PROJECT_ONLY
    }

    @Override
    boolean isIncremental() {
        return permissionExt.incrementalEnabled
    }

    @Override
    void transform(TransformInvocation invocation) throws TransformException, InterruptedException, IOException {
        def time = System.currentTimeMillis()
        Transformer transformer = Transformer.getTransformer(invocation, !permissionExt.parallelEnabled)
        transformer.transform()
        println("spent time = " + (System.currentTimeMillis() - time))
    }

}
